import styles from './index.module.scss'
import message from '@c/message'
import Image from '@c/image'
import { AREA_SEARCH_GET } from '@/constant'
import Link from 'next/link'
import cm from 'classnames'
import { useEffect, useState } from 'react'
import { useShowLogin, useWindowWidth } from '@/utils/hooks'
import { vodCollected, vodCancelCollected } from '@/api/history-collect'
import EventBus from '@/utils/emitter'
import { pcStore } from '@/store'
import { useRecoilValue } from 'recoil'

const updateCollectStatus = (data, id, val) => {
  const updateData = data.map(item => {
    if (item.id === id) {
      item.collect = val
    }
    return item
  })
  return updateData
}

const Index = props => {
  const {
    showTitle = true, //是否需要展示标题行
    data,
    isHome = false, //是否是首页
    source,
    top = 0,
    isDetail = false, //是否是详情页
    hideCollect = false,
    className,
    lessItems = false,
    isSearchPage,
    refresh = false
  } = props
  const pcState = useRecoilValue(pcStore)
  const setShowLogin = useShowLogin()
  const [list, setList] = useState(data.cards || [])
  const { count } = useWindowWidth()

  const toListUrl = tag => {
    if (!source) {
      return ''
    }
    if (isHome) {
      return source
    }
    return `${source}/all/all/${AREA_SEARCH_GET(source.slice(1), tag)}`
  }

  const collected = async (type, data) => {
    const token = localStorage.getItem('token')
    if (!token) {
      setShowLogin(true)
      return
    }
    let res = null
    if (type) {
      res = await vodCancelCollected(parseInt(data.id), token)
    } else {
      res = await vodCollected(parseInt(data.id), token)
    }
    if (!res.code) {
      message({ content: type ? '取消收藏成功' : '收藏成功！' })
      setList(updateCollectStatus(list, data.id, type ? 2 : 1))
      //做处理
    } else {
      message({ content: res.msg })
    }
  }

  // 收藏
  const toggleCollect = (e, data) => {
    e.stopPropagation()
    e.preventDefault()

    collected(data.collect === 1, data)
  }

  useEffect(() => {
    EventBus.on('firstLevelPage', res => {
      const currCards = res.find(item => item.name === data.name)?.cards || []
      setList(currCards)
    })
    return () => {
      EventBus.offAll('firstLevelPage')
    }
  }, [data.name])

  // 更新数据&用在搜素需要更新的页面
  useEffect(() => {
    setList(data.cards || [])
  }, [data])

  // 数据为空则渲染null
  if (!data.cards || !data.cards.length) return null

  const jump = (e, id) => {
    if (refresh) {
      e.preventDefault()
      window.location.replace(`/vod/detail/${id}`)
    }
  }
  return (
    <div
      className={cm(styles.list, styles.listPhone, isSearchPage ? '' : styles.needHorizon)}
      style={{ marginTop: top }}
    >
      {showTitle ? (
        isDetail ? (
          <div className={styles.title}>
            <h2 className={styles.tag}>{data?.name}</h2>
            {!data.ban ? (
              <div className={styles.more}>
                <span>探索全部</span>
                <span>{'>>'}</span>
              </div>
            ) : null}
          </div>
        ) : (
          <Link href={toListUrl(data?.name)} className={styles.title}>
            <h2 className={styles.tag}>{data?.name}</h2>
            {!data.ban ? (
              <div className={styles.more}>
                <span>探索全部</span>
                <span>{'>>'}</span>
              </div>
            ) : null}
          </Link>
        )
      ) : null}
      <div className={cm('items', styles.items, 'scrollBeautify', className)}>
        {list.map((item, index) => {
          let labelStr = item.label
          try {
            labelStr = JSON.parse(item.label).join(',')
          } catch (error) {}
          return (
            <figure
              title={item.desc || '暂无剧情简介信息'}
              key={index}
              className={cm('item', styles.item, styles.a, index + 1 > count * 2 && pcState && lessItems ? 'hide' : '')}
            >
              <Image className={styles.bg} src={item.img || item.picurl} alt={item.name || '详情海报'} />
              <Link
                href={`/vod/detail/${item.id}`}
                onClick={e => jump(e, item.id)}
                replace={isDetail}
                className={styles.detail}
              >
                <div className={cm(styles.bottomDetail, 'hideWhenPhone')}>
                  <div className="flex" style={{ marginBottom: 10 }}>
                    {item.tmdbScore ? (
                      <div className={styles.mark}>
                        <img loading="lazy" src="/images/tmdb.png" alt="tmdb" className={styles.tmdb} />
                        <span>{('' + item.tmdbScore).toFix(1)}</span>
                      </div>
                    ) : null}
                    {item.doubanScore ? (
                      <div className={styles.mark}>
                        <img loading="lazy" src="/images/douban.png" alt="douban" className={styles.douban} />
                        <span>{('' + item.doubanScore).toFix(1)}</span>
                      </div>
                    ) : null}
                  </div>
                  <p className={cm(styles.name, 'textEllipsis')}>{item.name}</p>
                  <div className={styles.type}>
                    <div className={styles.typeInfo}>
                      <p className="w-full textEllipsis">{labelStr || '暂无分类信息'}</p>
                      <p className={styles.countStr}>
                        <span>{item.time || '暂无上映日期'}</span>
                        <span>&nbsp;{item.countStr}</span>
                      </p>
                    </div>
                    {hideCollect ? null : (
                      <>
                        {item.collect === 1 ? (
                          <div
                            className={styles.addLove}
                            html-txt="从我的收藏移除"
                            onClick={e => toggleCollect(e, item)}
                          >
                            <img loading="lazy" src="/images/h-collected.png" alt="已经藏" />
                          </div>
                        ) : (
                          <div
                            className={styles.addLove}
                            html-txt="添加到我的收藏"
                            onClick={e => toggleCollect(e, item)}
                          >
                            <img loading="lazy" src="/images/h-collect.png" alt="添加收藏" />
                          </div>
                        )}
                      </>
                    )}
                  </div>
                  <p className={styles.desc}>{item.desc || '暂无剧情简介信息'}</p>
                </div>
                <div className={cm(styles.detailPhone, 'hideWhenPc')}>
                  <div className="flex mb-1">
                    {item.tmdbScore ? (
                      <div className={styles.mark}>
                        <img loading="lazy" src="/images/tmdb.png" alt="tmdb" className={styles.tmdb} />
                        <span>{('' + item.tmdbScore).toFix(1)}</span>
                      </div>
                    ) : null}
                    {item.doubanScore ? (
                      <div className={styles.mark}>
                        <img loading="lazy" src="/images/douban.png" alt="douban" className={styles.douban} />
                        <span>{('' + item.doubanScore).toFix(1)}</span>
                      </div>
                    ) : null}
                  </div>
                  <p className={cm(styles.name, 'textEllipsis')}>{item.name}</p>
                </div>
              </Link>
            </figure>
          )
        })}
      </div>
    </div>
  )
}

export default Index
